var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
var dateTimePicker = require('../../utils/dateTimePicker.js');
var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var PageBase = require('../../common/PageBase.js');
var app = getApp();

Page(common.extendPage(PageBase, {
  data: {
    currentAddr: {},
    date: '2018-10-01',
    time: '12:00',
    dateTimeArray: null,
    dateTime: null,
    startYear: 2000,
    endYear: 2050,
    storetype: null,
    depot: [],
    needRaise: false,
    needToHome: false,
    distance: 200,
    isSelectedTime: false,
    orderId: '',
    price: 0,
    totalPrice: 0,
    totalPriceAll: 0,
    shopName: '',
    beginAddr: '',
    endAddr: '',
    beginLng: '',
    beginLat: '',
    endLng: '',
    endLat: '',
    distance: 0,
    freight: '0.00',
    personPrice: '0.00',
    floorPrice: '0.00',
    cid:''
  },
  /**
   * 页面初始化
   */
  onLoad(options) {
    qqmapsdk = new QQMapWX({
      key: 'XJCBZ-ER6CO-7QEWS-SAUJY-2JXH7-56BQ5'
    });
    this._options = options;
    var storetype = this._options.storetype;
    console.log(options);

    var totalPrice = 0;
    this._psfee = 0;
    this._servicesNum = 0;
    if (this._options.depot && this._options.depot.length > 0) {
      var depot = JSON.parse(this._options.depot);
      console.log(depot);
      // this._materiaCost = 0;
      // this._labourCost = 0;
      depot.forEach((item, index) => {
        item.subtotalPrice = parseFloat(item.subtotalPrice).toFixed(2);
        totalPrice += parseFloat(item.subtotalPrice);
        if (item.psfee) {
          Object.keys(item.psfee).forEach((val, idx) => {
            if (val.substr(0, 3) == 'low') {
              this._psmost = val.substr(3, 2);
            }
          })
          this._servicesNumArr = [];
          item.services.forEach((val, idx) => {
            this._servicesNumArr.push(val.num);
          })
          this._servicesNum += Math.max.apply(null, this._servicesNumArr);
          this._psfee = this._servicesNum > this._psmost ? parseFloat(item.psfee['low' + this._psmost]) + item.psfee['up' + this._psmost] * (this._servicesNum - this._psmost) : item.psfee['low' + this._psmost];
        }
        if (item.services && item.services.length > 0) {
          item.services.forEach((val, idx) => {
            val.subtotalPrice = parseFloat(val.subtotalPrice).toFixed(2);
          })
        }
      })
      totalPrice += parseFloat(this._psfee);
      this.setData({
        depot,
        psfee: parseFloat(this._psfee).toFixed(2) || 0,
        totalPrice: parseFloat(totalPrice).toFixed(2)
      })
    }
    this.setData({
      shopName: this._options.shopName,
      storetype,
      cid:this._options.cid || ''
    })
    this.getDateTime();
  },
  /**
   * 页面重载
   */
  onShow() {
    var currentAddr = wx.getStorageSync('currentAddr');
    if (currentAddr) {
      this.setData({
        currentAddr
      })
    }

  },
  /**
   * 获取当前时间
   */
  getDateTime() {
    var obj = dateTimePicker.dateTimePicker(this.data.startYear, this.data.endYear);

    // 精确到分的处理，将数组的秒去掉
    var lastArray = obj.dateTimeArray.pop();
    var lastTime = obj.dateTime.pop();

    this.setData({
      dateTime: obj.dateTime,
      dateTimeArray: obj.dateTimeArray
    });
  },
  /**
   * 切换时间
   */
  changeDateTime(e) {
    this.setData({
      dateTime: e.detail.value
    });
    var arr = this.data.dateTime,
      dateArr = this.data.dateTimeArray;

    arr[e.detail.column] = e.detail.value;
    dateArr[2] = dateTimePicker.getMonthDay(dateArr[0][arr[0]], dateArr[1][arr[1]]);

    this.setData({
      dateTimeArray: dateArr,
      dateTime: arr,
      isSelectedTime: true
    });
  },
  /**
   * 是否需要人工搬运
   */
  _switch1(evt) {
    var {
      value
    } = evt.detail;
    this.setData({
      needToHome: !this.data.needToHome
    })
  },
  /**
   * 是否需要楼梯搬高
   */
  _switch2(evt) {
    var {
      value
    } = evt.detail;
    this.setData({
      needRaise: !this.data.needRaise
    })
  },
  /**
   * 订单信息提交
   */
  _submit(evt) {
    var {
      depot,
      storetype,
      currentAddr,
      isSelectedTime,
      dateTimeArray,
      dateTime,
      cid
    } = this.data;

    var {
      remark,
      startAddr,
      endAddr,
      contactsName,
      contactsNum,
      goodsDetail,
      goodsWeight,
      personNum,
      floorNum
    } = evt.detail.value;

    var paramsUrl = '/public/api/orders/addorder';
    var paramsData = {
      uid: wx.getStorageSync('uid'),
      mid: this._options.mid,
      services: {
        item: []
      }
    }
    if (storetype != 3) {
      if (JSON.stringify(this.data.currentAddr) == '{}') {
        util.tips('请输入地址信息');
        return false;
      }
    }
    if (isSelectedTime) {
      paramsData.yuyue = dateTimeArray[0][dateTime[0]] + '-' + dateTimeArray[1][dateTime[1]] + '-' + dateTimeArray[2][dateTime[2]] + ' ' + dateTimeArray[3][dateTime[3]] + ':' + dateTimeArray[4][dateTime[4]];
    } else {
      util.tips('请选择预约时间');
      return false;
    }

    if (remark) {
      paramsData.remark = remark;
    } else {
      util.tips('请输入备注信息');
      return false;
    }

    if (storetype != 3) {
      paramsData.username = this.data.currentAddr.username;
      paramsData.mobile = this.data.currentAddr.mobile;
      paramsData.address = this.data.currentAddr.addrText;
    } else {
      paramsData.address = startAddr;
      paramsData.address1 = endAddr;
      paramsData.username = contactsName;
      paramsData.mobile = contactsNum;
    }

    depot.forEach((item, index) => {
      var servicesItem = {};
      servicesItem.sid = item.sid;
      servicesItem.title = item.title;
      if (storetype == 1 || storetype == 8) {
        servicesItem.species = item.species;
        servicesItem.ways = item.way;
        servicesItem.specifications = item.specifications;
      }

      if (storetype == 2 || storetype == 9) {
        servicesItem.species = item.species;
        servicesItem.ways = item.way;
        servicesItem.specifications = item.specifications;
        servicesItem.amountList = {
          specifications: item.specificationsPrice
        }
      }

      if (storetype == 3) {
        servicesItem.details = goodsDetail;
        servicesItem.weight = goodsWeight;
        servicesItem.distance = this.data.distance;
        servicesItem.handling = personNum;
        servicesItem.jiashou = floorNum;
      }

      // if (storetype != 5 && storetype != 6) {
        if (item.services && item.services.length > 0) {
          var curService = [];
          item.services.forEach((val, idx) => {
            if (val.num > 0) {
              var curServiceStr = "";
              curServiceStr = val.title + ',' + val.unit + ',' + (val.zk_price ? val.zk_price : val.price) + ',' + val.num;
              curService.push(curServiceStr);
            }
          })
          servicesItem.services = curService;
        }
      // }
      paramsData.services.item.push(servicesItem);
    })

    paramsData.services = JSON.stringify(paramsData.services);
    ajax.P({
      url: paramsUrl,
      data: paramsData,
      success: (res, isLoadcb) => {
        var {
          ordernum,
          amount,
          oid
        } = res.data;
        this.setData({
          orderId: ordernum,
          price: amount
        })
        isLoadcb && isLoadcb();
        wx.redirectTo({
          url: '/pages/pay/index?ordernum=' + ordernum + '&amount=' + amount + '&orderId=' + oid + '&cid=' + cid
        })
      },
      fail: (res) => {
        console.log(res);
      }
    })
  },
  /**
   * 选择起始地址
   */
  _selectedAddr(evt) {
    var {
      curAddrType
    } = evt.currentTarget.dataset;
    if (!this.data.beginAddr && curAddrType == 'end') {
      util.tips('请先选择起始地点');
      return false;
    }
    wx.chooseLocation({
      success: (res) => {
        if (curAddrType == 'begin') {
          this.setData({
            beginAddr: res.name,
            beginLng: res.longitude,
            beginLat: res.latitude
          })
        } else {
          this.setData({
            endAddr: res.name,
            endLng: res.longitude,
            endLat: res.latitude
          })

          qqmapsdk.calculateDistance({
            //mode: 'driving',//可选值：'driving'（驾车）、'walking'（步行），不填默认：'walking',可不填
            //from参数不填默认当前地址
            //获取表单提交的经纬度并设置from和to参数（示例为string格式）
            from: {
              latitude: this.data.beginLat,
              longitude: this.data.beginLng
            } || '', //若起点有数据则采用起点坐标，若为空默认当前地址
            to: [{
              latitude: this.data.endLat,
              longitude: this.data.endLng
            }], //终点坐标
            success: (res) => { //成功后的回调
              var elements = res.result.elements;
              var distance = parseFloat(elements[0].distance / 1000).toFixed(1);
              if (this.data.storetype == 3) {
                this._freight = 0;
                this._totalPriceAll = 0;
                this._totalPrice = this.data.totalPrice;
                this.data.depot.forEach((item, index) => {
                  var freightItem = 0;
                  this._vehicleNum = 0;
                  if (distance > parseInt(item.distance.start_distance)) {
                    freightItem = parseFloat(item.distance.start_price) + parseInt(distance - item.distance.start_distance) * item.distance.more_price;
                  } else {
                    freightItem = item.distance.start_price;
                  }

                  item.services.forEach((val, idx) => {
                    if (val.num > 0) {
                      this._vehicleNum += parseInt(val.num);
                    }
                  })
                  this._freight += parseFloat(freightItem) * this._vehicleNum;
                })
                this._totalPriceAll += parseFloat(this._freight) + parseFloat(this._totalPrice);
              }
              this.setData({
                distance,
                totalPriceAll: parseFloat(this._totalPriceAll).toFixed(2),
                freight: parseFloat(this._freight).toFixed(2)
              })
            },
            fail: function(error) {
              console.error(error);
            },
            complete: function(res) {
              console.log(res);
            }
          });
        }
      }
    });
  },
  /**
   * 获取需要人工人数
   */
  _getPersonNum(evt) {
    var personNum = evt.detail.value;
    var depot = this.data.depot;
    this._totalPriceAll = 0;
    this._personPrice = 0;
    this._totalPrice = this.data.totalPrice;
    depot.forEach((item, index) => {
      this._personPrice += item.handling.price * personNum;
    })
    this._totalPriceAll += parseFloat(this._totalPrice) + parseFloat(this._personPrice) + parseFloat(this._freight)
    this.setData({
      totalPriceAll: parseFloat(this._totalPriceAll).toFixed(2),
      personPrice: parseFloat(this._personPrice).toFixed(2)
    })
  },
  _getFloorNum(evt) {
    var floorNum = evt.detail.value;
    var depot = this.data.depot;
    this._totalPriceAll = 0;
    this._floorPrice = 0;
    this._totalPrice = this.data.totalPrice;
    depot.forEach((item, index) => {
      this._floorPrice += item.jiashou.price * floorNum;
    })
    this._totalPriceAll += parseFloat(this._totalPrice) + parseFloat(this._personPrice) + parseFloat(this._freight) + parseFloat(this._floorPrice)
    this.setData({
      totalPriceAll: parseFloat(this._totalPriceAll).toFixed(2),
      floorPrice: parseFloat(this._floorPrice).toFixed(2)
    })
  }
}));